package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.gson.Gson;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-26
 */
@Service
@RequiredArgsConstructor
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{
    private final CheckInMapper checkInMapper;
    private final ElderServiceImpl elderService;
    private final BedServiceImpl bedService;
    private final CheckInConfigServiceImpl checkInConfigService;
    private final ContractServiceImpl contractService;


    // 查看入住详情
    @Override
    @Transactional
    public CheckInDetailVo selectDetailById(Long id) {
        CheckInDetailVo vo = new CheckInDetailVo();

        // 查看合同
        Contract contract = contractService.selectContractById(id);
        vo.setContract(contract);
        // 查看老人信息
        Long elderId = contract.getElderId();
        Elder elder = elderService.selectElderById(elderId);
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
            // 计算年龄
        LocalDate birthday = LocalDate.parse(elder.getBirthday());
        LocalDate now = LocalDate.now();
        Period period = Period.between(birthday,now);
        int age = period.getYears();
        checkInElderVo.setAge(age);
            // 家人信息
        String remark = elder.getRemark();
        List<ElderFamilyVo> family = JSON.parseArray(remark, ElderFamilyVo.class);
        vo.setElderFamilyVoList(family);
        vo.setCheckInElderVo(checkInElderVo);
        // 查看入住信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        CheckInConfig checkInConfig = checkInConfigService.selectCheckInConfigById(id);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkIn,checkInConfigVo);
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        vo.setCheckInConfigVo(checkInConfigVo);
        return vo;
    }


    // 入住申请
    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        // 检验老人是否已入住
            // 根据身份证查询老人的入住状态，状态为2,3,4的不能申请入住
        String idCardNo = checkInApplyDto.getCheckInElderDto().getIdCardNo();
        Elder elder = elderService.getOne(Wrappers.<Elder>lambdaQuery().in(Elder::getIdCardNo, idCardNo));
        if(elder != null){
            throw new BaseException("该老人不能申请入住");
        }
        // 更新床位状态为已入住
            // 根据床位id 修改床位状态
        Long bedId = checkInApplyDto.getCheckInConfigDto().getBedId();
        LambdaUpdateWrapper<Bed> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Bed::getId,bedId);
        wrapper.set(Bed::getBedStatus,Bed.BED_STATUS_APPLY);
        bedService.update(wrapper);
            // 根据床位id获得床位信息
        Bed bed = bedService.selectBedById(bedId);
        // 新增老人
        elder = new Elder();
        saveElder(checkInApplyDto,elder,bed);
        // 新增签约办理
        saveCheckInContractor(checkInApplyDto,elder);
        // 新增入住信息
        CheckIn checkIn = saveCheckIn(checkInApplyDto, elder, bed);
        // 新增入住配置
        saveCheckInConfig(checkInApplyDto,checkIn);
    }



    // 新增入住配置
    private void saveCheckInConfig(CheckInApplyDto checkInApplyDto,CheckIn checkIn) {
        CheckInConfigDto dto = checkInApplyDto.getCheckInConfigDto();
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto,checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigService.save(checkInConfig);
    }

    // 新增入住信息
    private CheckIn saveCheckIn(CheckInApplyDto checkInApplyDto,Elder elder,Bed bed) {
        CheckIn checkIn = new CheckIn();
        CheckInConfigDto dto = checkInApplyDto.getCheckInConfigDto();
        BeanUtils.copyProperties(dto,checkIn);
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(CheckIn.CHECK_IN_STATUS);
        super.save(checkIn);
        return checkIn;
    }

    // 新增签约办理
    private void saveCheckInContractor(CheckInApplyDto checkInApplyDto,Elder elder) {
        CheckInContractDto dto = checkInApplyDto.getCheckInContractDto();
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto,contract);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        String s = CodeGenerator.generateContractNumber();
        contract.setContractNumber("ht"+s);
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getFeeStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getFeeEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        Integer status = dto.getSignDate().isAfter(LocalDateTime.now()) ? Contract.CONTRACT_STATUS_OUT : Contract.CONTRACT_STATUS_IN;
        contract.setStatus(status);
        contractService.save(contract);
    }

    // 新增老人
    public void saveElder(CheckInApplyDto checkInApplyDto,Elder elder,Bed bed){
        CheckInElderDto dto = checkInApplyDto.getCheckInElderDto();
        BeanUtils.copyProperties(dto,elder);
        elder.setStatus(bed.getBedStatus());
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        List<ElderFamilyDto> list = checkInApplyDto.getElderFamilyDtoList();
        elder.setRemark(JSON.toJSONString(list));
        elderService.save(elder);
    }

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn)?1:0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn)?1:0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id)?1:0;
    }



}
